package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignClient;
import com.atguigu.gulimall.seckill.feign.ProductFeignClient;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionRelationVo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CouponFeignClient couponFeignClient;
    @Autowired
    ProductFeignClient productFeignClient;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void upSeckillSkuLatest3Days() {
        R r = couponFeignClient.getLatest3DaysSession();
        if (r.getCode() == 0) {
            List<SeckillSessionVo> data = r.getData(new TypeReference<List<SeckillSessionVo>>() {
            });
            if (data != null && data.size() > 0) {
                //缓存到redis
                //1，秒杀活动信息
                saveSessionInfo(data);
                //2.活动关联的商品信息
                saveSessionSkusInfo(data);
            }
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurSeckillSkus() {
        //1.确定当前时间处在哪个场次
        long now = new Date().getTime();
        String prefix = SESSIONS_CACHE_PREFIX + "*";
        Set<String> keys = redisTemplate.keys(prefix);
        for (String key : keys) {
            String[] timeStr = key.replace("seckill:sessions:", "").split("_");
            Long startTime = Long.parseLong(timeStr[0]);
            Long endTime = Long.parseLong(timeStr[1]);
            if (now >= startTime && now <= endTime) {
                //2.获取当前场次的商品信息
                List<String> sessionIdAndSkuIdList = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                if (sessionIdAndSkuIdList != null && sessionIdAndSkuIdList.size() > 0) {
                    List<String> list = hashOps.multiGet(sessionIdAndSkuIdList);
                    if (list != null && list.size() > 0) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject(String.valueOf(item), SeckillSkuRedisTo.class);
                            //   redisTo.setRandomCode("");秒杀开始的时候需要随机码
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                }
                break;
            }
        }
        return null;
    }


    private void saveSessionInfo(List<SeckillSessionVo> data) {
        for (SeckillSessionVo vo : data) {
            Long startTime = vo.getStartTime().getTime();
            Long endTime = vo.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;

            //上架了的场次不用再次上架，幂等性处理
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<SeckillSessionRelationVo> relationSkus = vo.getRelationSkus();
                if (relationSkus != null && relationSkus.size() > 0) {
                    List<String> relationIds = relationSkus.stream().map(e -> e.getPromotionSessionId() + "_" + e.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, relationIds);
                }
            }
        }

    }

    private void saveSessionSkusInfo(List<SeckillSessionVo> data) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        for (SeckillSessionVo vo : data) {
            List<SeckillSessionRelationVo> relationSkus = vo.getRelationSkus();
            for (SeckillSessionRelationVo sku : relationSkus) {
                //4.设置随机码
                String randomCode = UUID.randomUUID().toString().replace("-", "");

                //同一场次的相同的商品不用再次上架，幂等性处理
                if (!hashOps.hasKey(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString())) {
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    redisTo.setRandomCode(randomCode);

                    //1.查询sku的基本信息
                    R r = productFeignClient.info(sku.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfoVo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfoVo);
                    }
                    //2.sku的秒杀信息
                    BeanUtils.copyProperties(sku, redisTo);

                    //3.设置当前商品的秒杀时间
                    redisTo.setStartTime(vo.getStartTime().getTime());
                    redisTo.setEndTime(vo.getEndTime().getTime());

                    hashOps.put(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString(), JSON.toJSONString(redisTo));

                    //5.使用商品可以秒杀的数量作为分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    semaphore.trySetPermits(sku.getSeckillCount());
                }

            }
        }
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();

        List<SeckillSkuRedisTo> list = new ArrayList<>();

        long now = new Date().getTime();
        if (keys != null && keys.size() > 0) {
            String regex = "\\d+_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regex, key)) {
                    String redisStr = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(redisStr, SeckillSkuRedisTo.class);
                    if (now >= redisTo.getStartTime() && now <= redisTo.getEndTime()) {
                    } else {
                        redisTo.setRandomCode(null);
                    }
                    list.add(redisTo);
                }
            }
        }

        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String SeckillSkuRedisToStr = hashOps.get(killId);

        SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(SeckillSkuRedisToStr, SeckillSkuRedisTo.class);
        long now = new Date().getTime();
        Long startTime = seckillSkuRedisTo.getStartTime();
        Long endTime = seckillSkuRedisTo.getEndTime();
        Long ttl = endTime - startTime;
        //校验时间是否在秒杀时间
        if (now >= startTime && now <= endTime) {
            String skuId = seckillSkuRedisTo.getPromotionSessionId() + "_" + seckillSkuRedisTo.getSkuId();
            //校验随机码
            if (seckillSkuRedisTo.getRandomCode().equals(key) && killId.equals(skuId)) {
                //校验数量
                if (num <= seckillSkuRedisTo.getSeckillLimit()) {
                    //校验是否已经购买过
                    String keyStr = memberRespVo.getId() + "_" + skuId;
                    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(keyStr, String.valueOf(num), ttl, TimeUnit.MILLISECONDS);
                    if (aBoolean) {//占位成功，未购买过商品
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + key);
                        boolean flag = semaphore.tryAcquire(num);
                        if (flag) {
                            //获得信号量则秒杀成功
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo to = new SeckillOrderTo();
                            to.setOrderSn(timeId);
                            to.setMemeberId(memberRespVo.getId());
                            to.setNum(num);
                            to.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                            to.setSkuId(seckillSkuRedisTo.getSkuId());
                            to.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());
                            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", to);
                            return timeId;
                        } else {
                            return null;
                        }

                    } else {
                        return null;
                    }
                }
            } else {
                return null;
            }
        } else {
            return null;
        }

        return null;
    }

}
